import math
import os
import turtle
from tkinter import *
from tkinter import ttk

import ttkthemes

objTk = None

objR1 = None
objR2 = None
objR3 = None
objCycle = None
objTurtle = None

flagRun = False


def _begin():
    objTurtle.reset()

    global flagRun
    flagRun = True

    R = objR1.get()
    r = objR2.get()
    delta = objR3.get()
    cycles = objCycles.get()

    objTurtle.penup()
    objTurtle.goto(0, R - delta)
    objTurtle.pendown()

    for i in range(360 * cycles):
        if not flagRun:
            break

        # 小圆圆心位置
        rad = i * math.pi / 180
        x = (R - r) * math.sin(rad)
        y = (R - r) * math.cos(rad)

        # 小圆顶点位置
        rad2 = rad * R / r
        x -= (r - delta) * math.sin(rad2 - rad)
        y += (r - delta) * math.cos(rad2 - rad)

        objTurtle.goto(x, y)


def _end():
    global flagRun
    flagRun = False


def getCurrentDir():
    defaultPath = os.path.dirname(__file__)
    if defaultPath == '':
        import sys
        defaultPath = sys.path[0]

    return defaultPath

def on_closing():
    _end()
    objTk.destroy()

def main():
    global objTk
    objTk = Tk()
    objTk.title('Turtle with Tkinter')
    objTk.iconbitmap(os.path.join(getCurrentDir(), '../logo.ico'))  # 要点：解决pyinstall打包后的exe，运行时找不到资源
    objTk.resizable(width=False, height=False)

    style = ttkthemes.ThemedStyle(objTk)
    style.set_theme('ubuntu')

    global frame
    frame = ttk.Frame(objTk)
    frame.pack(fill=BOTH, expand=YES)

    row = 0
    Label(frame, text="框半径").grid(row=row, column=0, sticky=NSEW)
    global objR1
    objR1 = IntVar(value=400)
    Entry(frame, textvariable=objR1).grid(row=row, column=1, sticky=NSEW)
    row+=1

    Label(frame, text="圆片半径").grid(row=row, column=0, sticky=NSEW)
    global objR2
    objR2 = IntVar(value=210)
    Entry(frame, textvariable=objR2).grid(row=row, column=1, sticky=NSEW)
    row += 1

    Label(frame, text="圆孔半径").grid(row=row, column=0, sticky=NSEW)
    global objR3
    objR3 = IntVar(value=50)
    Entry(frame, textvariable=objR3).grid(row=row, column=1, sticky=NSEW)
    row += 1

    Label(frame, text="圈数").grid(row=row, column=0, sticky=NSEW)
    global objCycles
    objCycles = IntVar(value=20)
    Entry(frame, textvariable=objCycles).grid(row=row, column=1, sticky=NSEW)
    row += 1

    Button(frame, text="开始", command=_begin).grid(row=row, column=0, sticky=NSEW)
    Button(frame, text="停止", command=_end).grid(row=row, column=1, sticky=NSEW)
    row += 1

    canvas_main = Canvas(frame, width=800, height=800)
    canvas_main.grid(row=row, column=0, columnspan=2)
    row += 1

    global objTurtle
    objTurtle = turtle.RawTurtle(canvas_main)  # 参考：https://docs.python.org/zh-cn/3/library/turtle.html#turtle.RawTurtle
    objTurtle.speed(0)

    objTk.protocol("WM_DELETE_WINDOW", on_closing)
    objTk.mainloop()


if __name__ == '__main__':
    main()
